package com.flection.summer.rule;

import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.flection.summer.config.ConfigReader;
import com.flection.summer.loadbalance.RouteRandomLoadBalance;
import com.flection.summer.loadbalance.RuleRandomLoadBalance;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;

/**
 * 
 * @author thnl
 *
 */
public class MainZoneAvoidanceRule extends ZoneAvoidanceRule {

	@Autowired
	private ConfigReader configReader;

	@Autowired
	private RouteRandomLoadBalance<?> routeRandomLoadBalance;

	@PostConstruct
	private void initialize() {
		routeRandomLoadBalance = new RuleRandomLoadBalance(configReader);
	}

	@Override
	public Server choose(Object key) {
		List<Server> servers = getServerList(key);

		if (routeRandomLoadBalance.get() != null) {
			return routeRandomLoadBalance.choose(servers);
		}

		return super.choose(key);
	}

	private List<Server> getServerList(Object key) {
		return getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key);
	}
}